package practice_2025_8_3;

class Solution {
    public int countSubstrings(String s) {
        int n = s.length();
        // 创建 dp 表
        boolean[][] dp = new boolean[n][n];
        int count = 0;
        // 填表
        for(int i = n - 1; i >= 0; i--) {
            for(int j = i; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    if (i == j || i + 1 == j) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                if (dp[i][j]) {
                    count++;
                }
            }
        }
        return count;
    }

    public String longestPalindrome(String s) {
        // 中心扩展算法
        int begin = 0, count = 0;
        int len = s.length();
        for(int i = 0; i < len; i++) {
            // 扩展奇数长度字符串
            int left = i, right = i;
            while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            if (right - left - 1 > count) {
                begin = left + 1;
                count = right - left - 1;
            }
            // 扩展偶数长度字符串
            left = i;
            right = i + 1;
            while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            if (right - left - 1 > count) {
                begin = left + 1;
                count = right - left - 1;
            }
        }
        return s.substring(begin, begin + count);
    }
}